<?php

namespace app\api\service\balance;

use app\common\library\helper;
use app\api\model\Wxsetting as WxsettingModel;

class GoodsDeduct
{
    protected $goodsList;
    protected $wx_app_id;

    public function __construct($goodsList,$wxapp_id)
    {
        $this->goodsList = $goodsList;
        $this->wx_app_id = $wxapp_id;
    }

    public function setGoodsbalance($maxBalanceNumCount, $actualBalanceNum)
    {
        // 计算实际零钱抵扣数量
        $this->setGoodsListBalanceNum($maxBalanceNumCount, $actualBalanceNum);
        // 总抵扣数量
        $totalBalanceNum = helper::getArrayColumnSum($this->goodsList, 'balance_num');
        // 填充余数
        $this->setGoodsListBalanceNumFill($actualBalanceNum, $totalBalanceNum);
        $this->setGoodsListBalanceNumDiff($actualBalanceNum, $totalBalanceNum);
        // 计算实际零钱抵扣金额
        $this->setGoodsListBalanceMoney();
        return true;
    }

    /**
     * 计算实际零钱抵扣数量
     * @param $maxBalanceNumCount
     * @param $actualBalanceNum
     */
    private function setGoodsListBalanceNum($maxBalanceNumCount, $actualBalancesNum)
    {

       foreach ($this->goodsList as &$goods) {
            if (!$goods['is_balance_discount']) continue;
                if($maxBalanceNumCount * $actualBalancesNum<=0){
                    $goods['balance_num'] = 0;
            }else{
                $goods['balance_num'] = helper::number2($goods['max_balance_num'] / $maxBalanceNumCount * $actualBalancesNum);
            }
        
        }
    }

    /**
     * 计算实际零钱抵扣金额
     */
    private function setGoodsListBalanceMoney()
    {

        $model = new WxsettingModel;
        $setting = $model->info($this->wx_app_id);
        foreach ($this->goodsList as &$goods) {
            if (!$goods['is_balance_discount']) continue;
            $goods['balance_money'] = $goods['balance_num'];

        }
    }

    private function setGoodsListBalanceNumFill($actualBalanceNum, $totalBalanceNum)
    {
        if ($totalBalanceNum === 0) {
            $temReducedMoney = $actualBalanceNum;
            foreach ($this->goodsList as &$goods) {
                if (!$goods['is_balance_discount']) continue;
                if ($temReducedMoney === 0) break;
                $goods['balance_num'] = 1;
                $temReducedMoney--;
            }
        }
        return true;
    }

    private function setGoodsListBalanceNumDiff($actualBalanceNum, $totalBalanceNum)
    {
        $tempDiff = $actualBalanceNum - $totalBalanceNum;
        foreach ($this->goodsList as &$goods) {
            if (!$goods['is_balance_discount']) continue;
            if ($tempDiff < 1) break;
            $goods['balance_num'] = $goods['balance_num'] + 1;
            $tempDiff--;
        }
        return true;
    }

}